package demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/13 15:55
 */
@Slf4j
public class OrderDelay implements Delayed {
    private String orderId;
    private Long timeout;

    OrderDelay(String orderId, long timeout) {
        this.orderId = orderId;
        this.timeout = timeout + System.nanoTime();
        log.debug("创建订单：{},{}s后过期", orderId, timeout/1_000_000_000);
    }

    @Override
    public int compareTo(Delayed other) {
        if (other == this) {
            return 0;
        }
        OrderDelay t = (OrderDelay) other;
        long d = (getDelay(TimeUnit.NANOSECONDS) - t.getDelay(TimeUnit.NANOSECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

    /**
     * 返回距离你自定义的超时时间还有多少
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    public void print() {
        log.debug(orderId + "编号的订单要删除啦。。。。");
    }

}
